<?php
/**
 * 百度鹰眼接口基类
 */
class LbsApiBasic
{
	/* 基础地址 */
	private $api_url = 'http://api.map.baidu.com/trace/v1/';
	
	/* 用户的ak，授权使用 */
	private $ak = 'a2jqqsMtw8baVelGGnt3ivfB';
	
	/* 服务ID */
	private $service_id = 0;
	
	/* 返回值 */
	private $response = array();
	
	public function __construct($type){
		$this->api_url .= "$type/";
	}
	
	protected function post($method,$data=array())
	{
		$data['ak'] = $this->ak;
		if($this->service_id > 0){
			$data['service_id'] = $this->service_id;
		}
		$url = $this->api_url.$method;
		return $this->curlpost($url,$data);
	}
	
	protected function get($method,$data=array())
	{
		$url = $this->api_url.$method;
		$requestStr = 'ak='.$this->ak;
		$requestStr = $this->service_id == 0 ? $requestStr : $requestStr.'&service_id='.$this->service_id;
		foreach ($data as $key=>$val)
		{
			$requestStr .= "&$key=".$val;
		}
		$url .= '?'.$requestStr;
		return $this->curlget($url);
	}
	
	protected function response($str)
	{
		$this->response = json_decode($str,true);
		if(is_array($this->response) && $this->response['status'] == 0){
			return $this->response;
		}else{
			return false;
		}
	}
	
	private function curlpost($url,$data)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$output = curl_exec($ch);
		curl_close($ch);
		return $this->response($output);
	}
	
	private function curlget($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);
		curl_close($ch);
		return $this->response($output);
	}
	
	public function setServiceId($service_id=0)
	{
		$this->service_id = $service_id;
	}
	
	public function getResponse()
	{
		return $this->response;
	}
}
?>